package org.example.domain.strategy.service.rule.chain.impl;


import lombok.extern.slf4j.Slf4j;
import org.example.domain.strategy.repository.IStrategyRepository;
import org.example.domain.strategy.service.armory.IStrategyDispath;
import org.example.domain.strategy.service.rule.chain.AbstractLogicChain;
import org.example.domain.strategy.service.rule.chain.factory.DefaultChainFactory;
import org.example.types.common.Constants;
import org.springframework.stereotype.Component;

import javax.annotation.Resource;
import java.util.*;

@Slf4j
@Component("rule_weight")
public class RuleWeightLogicChain extends AbstractLogicChain {

    @Resource
    private IStrategyRepository repository;
    @Resource
    private IStrategyDispath strategyDispath;

    public Long userScore = 0L;

    @Override
    protected String ruleModel() {
        return "rule_weight";
    }

    @Override
    public DefaultChainFactory.StrategyAwardVO logic(String userId, Long strategyId) {
        log.info("抽奖责任链——权重开始 userId:{} strategyId:{} ruleModel:[}",userId,strategyId,ruleModel());

        //查询规则值配置
        String ruleValue = repository.queryStrategyRuleValue(strategyId, ruleModel());


        //1.分析ruleValue   [key: 4000  value: 4000:102,103,104,105]
        Map<Long, String> analyticalValueGroup = getAnalyticalValue(ruleValue);

        if(null == analyticalValueGroup || analyticalValueGroup.isEmpty()){return null;}

        //2.转换Keys值，并默认排序
        List<Long> analyticalSortedKeys = new ArrayList<>(analyticalValueGroup.keySet());
        Collections.sort(analyticalSortedKeys);

        //3. 找出最大符合值，也就是【4500积分，能找到4000：102,103,104,105】
        /**
         * nextValue = analyticalSortedKeys.stream()
         *                      .sorted(Comparator.reverseOrder())
         *                      .filter(key -> userScore >= key)
         *                      .findFirst()
         *                      .orElse(null);
         */
//        Long nextValue = analyticalSortedKeys.stream()
//                .filter(key -> userScore >= key)
//                .max(Comparator.naturalOrder())
//                .orElse(null);
        Integer userScore = repository.queryActivityAccountTotalUseCount(userId, strategyId);
        Long nextValue = analyticalSortedKeys.stream()
                .sorted(Comparator.reverseOrder())
                .filter(analyticalSortedKeyValue -> userScore >= analyticalSortedKeyValue)
                .findFirst()
                .orElse(null);

        //4.权重抽奖
        if(null != nextValue){
            Integer awardId = strategyDispath.getRandomAwardId(strategyId, analyticalValueGroup.get(nextValue));
            log.info("抽奖责任链——权重接管 userId:{} strategyId:{} ruleModel:[},awardId:{}",userId,strategyId,ruleModel(),awardId);
            return DefaultChainFactory.StrategyAwardVO.builder()
                    .awardId(awardId)
                    .logicModel(ruleModel())
                    .build();
        }


        return next().logic(userId,strategyId);
    }

    private Map<Long,String> getAnalyticalValue(String ruleValue){

        String[] ruleValueGroup = ruleValue.split(Constants.SPACE);
        Map<Long,String> ruleValueMap = new HashMap<>();
        for(String ruleValueKey : ruleValueGroup){
            //检查输入是否为空
            if(ruleValueKey == null || ruleValueKey.isEmpty()){
                return ruleValueMap;
            }

            //分割字符串以获取键和值
            String[] parts = ruleValueKey.split(Constants.COLON);
            if(parts.length != 2){
                throw new IllegalArgumentException("rule_weight rule_rule invalid input format" + ruleValueKey);
            }
            ruleValueMap.put(Long.valueOf(parts[0]),ruleValueKey);
        }

        return ruleValueMap;
    }
}
